package com.aoxon.cargo.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aoxon.cargo.R;
import com.aoxon.cargo.bean.GsonBean;
import com.aoxon.cargo.bean.Picture;
import com.aoxon.cargo.bean.Supplier;
import com.aoxon.cargo.cache.FileManager;
import com.aoxon.cargo.cache.SupCache;
import com.aoxon.cargo.component.MyCallBack;
import com.aoxon.cargo.component.MyListDialog;
import com.aoxon.cargo.component.MyProgressDialog;
import com.aoxon.cargo.component.MySquarePicture;
import com.aoxon.cargo.loader.NormalDataLoader;
import com.aoxon.cargo.service.FileUpLoadService;
import com.aoxon.cargo.service.MyServiceFactory;
import com.aoxon.cargo.service.RevampStoreService;
import com.aoxon.cargo.shared.SupIndexShared;
import com.aoxon.cargo.state.DataState;
import com.aoxon.cargo.state.MyReturnState;
import com.aoxon.cargo.state.MyStateUtil;
import com.aoxon.cargo.util.CheckStateUtil;
import com.aoxon.cargo.util.DataUtil;
import com.aoxon.cargo.util.EnvironmentUtil;
import com.aoxon.cargo.util.ImageUtil;
import com.aoxon.cargo.util.ToastUtil;
import com.google.gson.JsonSyntaxException;

public class SupFillInfo4Activity extends BaseActivity implements
		NormalDataLoader.OnLoadDataListener {
	private String tag = "SupFillInfo4Activity";

	private ImageView ivReturn, ivAddPicture;
	private TextView tvFinish;
	private LinearLayout llPicture;

	boolean update = false;
	private Supplier supplier;
	private FileManager imageManager = new FileManager();
	private MyListDialog myListDialog;
	private FileUpLoadService fileUpLoadService = new FileUpLoadService();
	private RevampStoreService revampStoreService = (RevampStoreService) MyServiceFactory
			.getInstance(MyServiceFactory.REVAMP_STORE);
	private NormalDataLoader normalDataLoader = new NormalDataLoader(this);
	private List<Picture> pictureList = new ArrayList<Picture>();
	private MySquarePicture mySquarePicture;
	private MyProgressDialog myProgressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setup();
	}

	private void setup() {
		setContentView(R.layout.sup_fill_info4);
		ivReturn = (ImageView) findViewById(R.id.ivPublicTitleReturn);
		ivAddPicture = (ImageView) findViewById(R.id.ivAddPicture_fill_info4);
		llPicture = (LinearLayout) findViewById(R.id.llShopPictures_fill_info4);
		tvFinish = (TextView) findViewById(R.id.tvFinish_fill_info4);
		ivReturn.setOnClickListener(onClick);
		ivAddPicture.setOnClickListener(onClick);
		tvFinish.setOnClickListener(onClick);

		myProgressDialog = new MyProgressDialog(this);
		normalDataLoader.setOnloadDataListener(this);
		mySquarePicture = new MySquarePicture(this, llPicture, true);
		myListDialog = new MyListDialog(this);
		showInit();
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		String path;
		Bitmap bitmap;
		Picture picture = new Picture();
		picture.setPictureState(DataState.INITIAL);

		switch (requestCode) {
		case MyStateUtil.FOLDER_for_FECADE:

			try {
				path = ImageUtil.getAbsoluteImagePath(data.getData(), this);
				bitmap = ImageUtil.getImageBitmap(path, 200, 200);
				if (bitmap.getWidth() < 200 || bitmap.getHeight() < 200) {
					ToastUtil.show(SupFillInfo4Activity.this,
							"图片分辨率不要小于200x200");
					Log.v(tag, " 图片太小 不要小于200x200 ");
				} else {
					mySquarePicture.getImageView(path, false);
					picture.setPictureUrl(path);
					picture.setPictureType(MyReturnState.STALL_TYPE);
					picture.setPictureState(DataState.INITIAL);
					pictureList.add(picture);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				Log.v(tag, " 图片太小 ");
				e.printStackTrace();
			}
			break;
		case MyStateUtil.CAMERA_for_FECADE:
			try {
				bitmap = data.getParcelableExtra("data");
				path = imageManager.saveBitmap(bitmap);
				mySquarePicture.getImageView(path, false);
				picture.setPictureUrl(path);
				picture.setPictureType(MyReturnState.STALL_TYPE);
				pictureList.add(picture);
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;

		case MyStateUtil.CAMERA_TO_ADD:
			Log.v(tag + "CAMERA_TO_ADD", " case");
		case MyStateUtil.GALLERY_RETURN:
			// llPicture.removeAllViews();
			Log.v(tag + "GALLERY_RETURN",
					DataUtil.gson.toJson(SupCache.pictureList));
			try {
				for (int i = 0; i < SupCache.pictureList.size(); i++) {

					picture = SupCache.pictureList.get(i);
					if (picture.getPictureState() == DataState.CAMERE_INITIAL) {
						picture.setPictureState(DataState.INITIAL);
						mySquarePicture.show(picture);
					}

				}
				pictureList = SupCache.pictureList;
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		}
	};

	OnClickListener onClick = new OnClickListener() {
		@Override
		public void onClick(View view) {
			// TODO Auto-generated method stub
			switch (view.getId()) {
			case R.id.tvFinish_fill_info4:
				normalDataLoader.load();
				CargoActivity.OPEN_CHOOSE = MyStateUtil.OPEN_MORE;
				Intent intentMore = new Intent(SupFillInfo4Activity.this,
						CargoActivity.class);
				startActivity(intentMore);
				break;
			case R.id.ivPublicTitleReturn:
				finish();
				break;
			case R.id.ivAddPicture_fill_info4:
				myListDialog.show("请选择", new String[] { "拍照", "本地文件" },
						new TakePhotoForStoreFecade());
				break;
			}
		}
	};

	private void showInit() {
		supplier = SupIndexShared.getSupplier();
		Log.v(tag, DataUtil.gson.toJson(supplier));
		if (supplier != null && supplier.getSupCompanyPicture() != null) {
			for (int i = 0; i < supplier.getSupCompanyPicture().size(); i++) {
				Picture picture = supplier.getSupCompanyPicture().get(i);
				if (picture.getPictureState() == DataState.SUCCESS) {
					mySquarePicture.show(picture);
					pictureList.add(picture);
				}

			}
			SupCache.pictureList = pictureList;
		}

	}

	class TakePhotoForStoreFecade implements MyCallBack {
		@Override
		public void callback(String choose) {
			SupCache.from = 110;
			if (choose.equals("拍照")) {
				if (!SupCache.initialCamera) {
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					startActivityForResult(intent,
							MyStateUtil.CAMERA_for_FECADE);
				} else {
					Intent intent = new Intent(getBaseContext(),
							SupCameraActivity.class);
					SupCache.pictureList = pictureList;
					startActivityForResult(intent, MyStateUtil.CAMERA_TO_ADD);
				}
			} else {
				try {
					Intent intent = new Intent(
							Intent.ACTION_PICK,
							android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
					startActivityForResult(intent,
							MyStateUtil.FOLDER_for_FECADE);
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}
	}

	@Override
	public void beforeLoad() {
		// TODO Auto-generated method stub
		myProgressDialog.show("提示", "提交中，请稍候...");
	}

	@Override
	public void toLoad(Message msg) throws Exception {
		// TODO Auto-generated method stub
		
		// List<Picture> list = SupCache.pictureList;
		for (int i = 0; i < pictureList.size(); i++) {
			Picture picture = pictureList.get(i);
			if (picture.getPictureState() == DataState.INITIAL) {
				GsonBean gsonBean = fileUpLoadService.upLoadPicture(picture
						.getPictureUrl());
				Log.v("pictrue return ", DataUtil.gson.toJson(gsonBean));
				update = true;
				try {
					if (CheckStateUtil.check(SupFillInfo4Activity.this,
							gsonBean, "更新")) {
						Picture pictureReturn = DataUtil.gson.fromJson(
								gsonBean.getStrJson(), Picture.class);
						pictureList.set(i, pictureReturn);
					}
				} catch (JsonSyntaxException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			if (picture.getPictureState() == DataState.DELETE) {
				update = true;
			}

		}
		if (update) {

			supplier.setSupCompanyPicture(pictureList);
			if (EnvironmentUtil.checkNetState(getBaseContext())) {
				GsonBean gsonBean = revampStoreService.execute(supplier);
				if (CheckStateUtil.check(gsonBean)) {

					SupIndexShared.saveSupplierAndKey(DataUtil.gson
							.toJson(supplier));
					// Log.v(tag, DataUtil.gson.toJson(supplier.getSupLogo()));
				}
				msg.what = MyStateUtil.UPLOAD_RESULT;
			} else {
				msg.what = MyStateUtil.NOT_NET_CONNECTION;
			}
		}

//		tvFinish.setClickable(true);

	}

	@Override
	public void afterLoad(int state) {
		// TODO Auto-generated method stub
		
		myProgressDialog.cancle();
		if(update){
			switch (state) {
			case MyStateUtil.UPLOAD_RESULT:
				ToastUtil.show(getBaseContext(), "上传成功");
				break;
			case MyStateUtil.UPLOAD_ERROR:
				ToastUtil.show(getBaseContext(), "上传出错，请重新提交");
				break;
			case MyStateUtil.RETURN_FAIL:
				ToastUtil.show(getBaseContext(), "无对应数据");
				break;
			case MyStateUtil.NOT_NET_CONNECTION:
				ToastUtil.show(getBaseContext(), "无网络连接");
				break;
			case MyStateUtil.ERROR_NET_CONNECTION:
				ToastUtil.show(getBaseContext(), "网络连接异常");
				break;
			default:
				ToastUtil.show(getBaseContext(), "上传出错，请重新提交");
				break;
			
			}
		}
		
	}

}
